package com.zmn.oms.business.impl.refund;

import com.zmn.oms.business.interfaces.refund.OrderRefundBService;
import com.zmn.oms.model.entity.pay.OrderPay;
import com.zmn.oms.services.interfaces.pay.OrderPayService;
import com.zmn.pay.common.constant.PayConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：退款
 *
 * @author heciqi
 * @date 2019/08/09 16:55
 */
@Slf4j
@Service
public class OrderRefundBServiceImpl implements OrderRefundBService {

    @Autowired
    private OrderPayService orderPayService;


    /**
     * 是否支持原路返回
     *
     * @param orderId
     * @return
     */
    @Override
    public boolean supportBacktracking(Long orderId) {
        // 过滤出支付记录
        List<OrderPay> orderPays = orderPayService.listOrderPayByOrderId(orderId)
                .stream()
                .filter(
                        e -> Objects.equals(e.getTradeType(), PayConsts.PAY_TRADE_TYPE_INTIME)
                                && !Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_DISCOUNT)
                )
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(orderPays)) {
            return false;
        }

        // 厂商的授信和余额支付可以原路返回
        boolean isFactoryPay = orderPays.stream()
                .allMatch(e -> Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_BALANCEAMOUNT)
                        || Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_CREDIT));

        if (isFactoryPay) {
            return true;
        }

        // 必须全是线上支付才能原路返回
        boolean isAllOnlinePay = orderPays.stream()
                .filter(e -> !Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_DISCOUNT))
                .allMatch(e -> PayConsts.REAL_PAY_CHANNEL.contains(e.getPayChannelId()));
        if (!isAllOnlinePay) {
            return false;
        }

        // 存在app支付（可能为工程师支付），不能原路返回
        boolean isMasterPay = orderPays.stream()
                .anyMatch(e -> Objects.equals(e.getPayType(), PayConsts.PAY_TYPE_APP)
                );
        if (isMasterPay) {
            return false;
        }

        return true;
    }

}
